/* eslint-disable*/
function indexedDB(keyword, type,raceid,value,callback) {
	//传入五个参数，键，方式，赛事id，要保存的内容，回调函数;indexedDB默认的数据库在下面
	var db;
	var request;
	var objectStore;
	var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB;
	//判断是否浏览器支持IndexedDB数据库
	if(indexedDB) {
		//支持走IndexedDB
		//1、打开或创建数据库
		//参数为：数据库名和版本号；数据库存在，则打开它；否则创建
		var dbName = 'ihp'+ raceid;
		var request = indexedDB.open(dbName,raceid);
		//2、指定操作成功的处理函数(可以获得对象存储空间信息)
		request.onsuccess = function(event) {
			db = event.target.result;
			var transaction = db.transaction(['info'], 'readwrite');
			objectStore = transaction.objectStore('info');
			if(type == 'get'){
			 //按照id查询
	         var requestGet = objectStore.get(keyword);
		      requestGet.onsuccess=function(e){
		      	  var responds = e.target.result;
            if(typeof callback === "function"){
              if(!responds){
                return callback(responds);
              }else{
                return callback(responds.data);
              }
            }
		      }
			} else if(type == 'set') {
				var detail={
					id:keyword,
					data:value
				};
	         var requestSet = objectStore.put(detail);
        requestSet.onsuccess=function(e){
          var responds = e.target.result;
          if(typeof callback === "function"){
            if(!responds){
              return callback(responds);
            }else{
              return callback(responds.data);
            }
          }
        }
			   requestSet.onerror = function(e) {
				 console.log(e.target.errorCode);
			   };
			}else if(type=='remove'){
	         var requestRemove = objectStore.delete(keyword);
		      requestRemove.onsuccess=function(e){
		          return callback(e);
		      };
			   requestRemove.onerror = function(e) {
				 console.log(e.target.errorCode);
			   };
			} else if(type == 'add') {
				var detailAdd={
					id:keyword,
					data:value
				};
	         var requestAdd = objectStore.add(detailAdd);
		      requestAdd.onsuccess=function(e){
//		          console.log(e.target);
		      };
			   requestAdd.onerror = function(e) {
				 console.log(e);
			   };
			}
//
		};
		//3、指定操作失败的处理函数
		request.onerror = function(e) {
			console.log(3)
			console.log(e.target);
		};
		//4、onupgradeneeded事件在下列情况下被触发：数据库第一次被打开时；打开数据库时指定的版本号高于当前被持久化的数据库版本号。(可通过修改版本号触发该事件)
		request.onupgradeneeded = function(e) {
			console.log(4)
			db = e.target.result; //获得数据库实例对象
			 objectStore = db.createObjectStore('info', {
				keyPath: 'id',
				autoIncrement: true
			});
		}
	} else {
		console.log('很抱歉，我的浏览器比较LOW')
		//不支持，走localStorage
		if(type== 'get') {
			return window.localStorage.getItem(keyword);
		} else if(type == 'set'||type== 'add') {
			return window.localStorage.setItem(keyword,value);
		}else if(type == 'remove'){
			return window.localStorage.removeItem(keyword);
		}

	}
}

export {
	indexedDB
}
